#!/usr/bin/env node
import app from './app';
import http from 'http';
import { PORT } from './config';
import connectMongo from './utils/connet-mongo';

const port = normalizePort(process.env.PORT || PORT || '3000');
const envName = process.env.NODE_ENV === 'production' ? '生产' : '开发';

/**
 * 格式化端口数字
 */
function normalizePort(val) {
  const port = parseInt(val, 10);
  if (isNaN(port)) {
    return val;
  }
  if (port >= 0) {
    return port;
  }
  return false;
}

/**
 * 数据库连接错误回调
 */
function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }
  const bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

connectMongo().then(() => {
  const server = http.createServer(app.callback());
  server.listen(port);
  server.on('error', onError);
  server.on('listening', () => {
    const addr = server.address();
    const bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr?.port;
    console.debug(`${envName}服务已经在${bind}端口上启动...`);
  });
});
